from fastapi import APIRouter, HTTPException, Depends, Query
from typing import List, Optional

from backend.schemas.user import (
    DepartmentCreate, DepartmentOut, DepartmentUpdate, DepartmentList, 
    DepartmentTree, DepartmentTreeNode, PaginationParams, PermissionOut,
    DepartmentPermissionAssign, DepartmentWithPermissions
)
from backend.services.user_service import DepartmentService, PermissionService
from backend.common.jwt import get_current_active_user, get_current_admin_user, require_permissions
from backend.schemas.response import ResponseBase
from backend.models.user import User, Permission

router = APIRouter()

@router.get("/department", response_model=ResponseBase[DepartmentList], summary="获取部门列表")
async def get_departments(
    pagination: PaginationParams = Depends(),
    current_user: User = Depends(require_permissions(["department:list"]))
):
    """获取部门列表，分页展示"""
    departments, total = await DepartmentService.get_departments(
        page=pagination.page, 
        limit=pagination.limit
    )
    
    department_list = []
    for dept in departments:
        parent = None
        if dept.parent_id:
            parent = await DepartmentService.get_department_by_id(dept.parent_id)
        
        department_list.append(DepartmentOut(
            id=dept.id,
            dept_id=dept.dept_id,
            dept_name=dept.dept_name,
            description=dept.description,
            parent_id=dept.parent_id,
            parent_name=parent.dept_name if parent else None,
            order_num=dept.order_num,
            ancestors=dept.ancestors,
            level=dept.level,
            created_at=str(dept.created_at),
            updated_at=str(dept.updated_at)
        ))
    
    return ResponseBase[DepartmentList](data=DepartmentList(
        items=department_list,
        total=total
    ))

@router.get("/department/tree", response_model=ResponseBase[DepartmentTree], summary="获取部门树结构")
async def get_department_tree(
    current_user: User = Depends(get_current_active_user)
):
    """获取部门树结构，用于前端展示"""
    try:
        tree_data = await DepartmentService.get_department_tree()
        return ResponseBase[DepartmentTree](data=DepartmentTree(
            items=tree_data
        ))
    except Exception as e:
        import traceback
        traceback.print_exc()
        raise HTTPException(status_code=500, detail=f"获取部门树失败: {str(e)}")

@router.post("/department", response_model=ResponseBase[DepartmentOut], summary="创建部门")
async def create_department(
    department: DepartmentCreate,
    current_user: User = Depends(require_permissions(["department:create"]))
):
    """创建新部门"""
    try:
        new_department = await DepartmentService.create_department(
            name=department.dept_name,
            description=department.description,
            parent_id=department.parent_id,
            order_num=department.order_num
        )
        
        return ResponseBase[DepartmentOut](
            data=DepartmentOut(
                id=new_department.id,
                dept_id=new_department.dept_id,
                dept_name=new_department.dept_name,
                description=new_department.description,
                parent_id=new_department.parent_id,
                order_num=new_department.order_num,
                ancestors=new_department.ancestors,
                level=new_department.level,
                created_at=str(new_department.created_at),
                updated_at=str(new_department.updated_at)
            ),
            message="部门创建成功"
        )
    except ValueError as e:
        raise HTTPException(status_code=400, detail=str(e))

@router.put("/department/{department_id}", response_model=ResponseBase[DepartmentOut], summary="更新部门")
async def update_department(
    department_id: str,
    department: DepartmentUpdate,
    current_user: User = Depends(require_permissions(["department:update"]))
):
    """更新部门信息"""
    try:
        dept_data = department.dict(exclude_unset=True)
        updated_department = await DepartmentService.update_department(department_id, dept_data)
        
        if not updated_department:
            raise HTTPException(status_code=404, detail="部门不存在")
            
        return ResponseBase[DepartmentOut](
            data=DepartmentOut(
                id=updated_department.id,
                dept_id=updated_department.dept_id,
                dept_name=updated_department.dept_name,
                description=updated_department.description,
                parent_id=updated_department.parent_id,
                order_num=updated_department.order_num,
                ancestors=updated_department.ancestors,
                level=updated_department.level,
                created_at=str(updated_department.created_at),
                updated_at=str(updated_department.updated_at)
            ),
            message="部门更新成功"
        )
    except ValueError as e:
        raise HTTPException(status_code=400, detail=str(e))
    except Exception as e:
        if "Duplicate entry" in str(e) and "department.dept_id" in str(e):
            raise HTTPException(status_code=400, detail=f"部门ID已存在，请更换其他ID")
        raise

@router.delete("/department/{department_id}", response_model=ResponseBase, summary="删除部门")
async def delete_department(
    department_id: str,
    current_user: User = Depends(require_permissions(["department:delete"]))
):
    """删除部门"""
    try:
        success = await DepartmentService.delete_department(department_id)
        
        if not success:
            raise HTTPException(status_code=404, detail="部门不存在")
            
        return ResponseBase(message="部门删除成功")
    except ValueError as e:
        raise HTTPException(status_code=400, detail=str(e))

@router.get("/department/{department_id}", response_model=ResponseBase[DepartmentOut], summary="获取部门详情")
async def get_department(
    department_id: str,
    current_user: User = Depends(require_permissions(["department:list"]))
):
    """获取部门详情"""
    print(f"获取部门详情，ID: {department_id}, 类型: {type(department_id)}")
    
    department = await DepartmentService.get_department_by_id(department_id)
    
    if not department:
        print(f"未找到部门，ID: {department_id}")
        raise HTTPException(status_code=404, detail="部门不存在")
    
    print(f"找到部门: {department.dept_name}, ID: {department.id}, dept_id: {department.dept_id}")
    
    # 获取父部门信息
    parent = None
    if department.parent_id:
        parent = await DepartmentService.get_department_by_id(department.parent_id)
        if parent:
            print(f"找到父部门: {parent.dept_name}")
        else:
            print(f"未找到父部门，ID: {department.parent_id}")
            
    return ResponseBase[DepartmentOut](
        data=DepartmentOut(
            id=department.id,
            dept_id=department.dept_id,
            dept_name=department.dept_name,
            description=department.description,
            parent_id=department.parent_id,
            parent_name=parent.dept_name if parent else None,
            order_num=department.order_num,
            ancestors=department.ancestors,
            level=department.level,
            created_at=str(department.created_at),
            updated_at=str(department.updated_at)
        )
    ) 

@router.get("/department/{department_id}/permissions", response_model=ResponseBase[List[PermissionOut]], summary="获取部门拥有的权限")
async def get_department_permissions(
    department_id: str,
    current_user: User = Depends(require_permissions(["department:permission:list"]))
):
    """获取部门拥有的权限列表"""
    try:
        permissions = await DepartmentService.get_department_permissions(department_id)
        
        permission_list = [
            PermissionOut(
                id=perm.id,
                name=perm.name,
                code=perm.code,
                description=perm.description,
                created_at=str(perm.created_at),
                updated_at=str(perm.updated_at)
            )
            for perm in permissions
        ]
        
        return ResponseBase[List[PermissionOut]](data=permission_list)
    except ValueError as e:
        raise HTTPException(status_code=404, detail=str(e))
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取部门权限失败: {str(e)}")

@router.post("/department/{department_id}/permissions", response_model=ResponseBase, summary="设置部门权限")
async def set_department_permissions(
    department_id: str,
    permissions: DepartmentPermissionAssign,
    current_user: User = Depends(require_permissions(["department:permission:update"]))
):
    """设置部门权限（替换现有权限）"""
    try:
        await DepartmentService.assign_permissions_to_department(
            department_id=department_id,
            permission_ids=permissions.permission_ids
        )
        
        return ResponseBase(message="部门权限设置成功")
    except ValueError as e:
        raise HTTPException(status_code=400, detail=str(e))
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"设置部门权限失败: {str(e)}")

@router.put("/department/{department_id}/permissions", response_model=ResponseBase, summary="添加部门权限")
async def add_department_permissions(
    department_id: str,
    permissions: DepartmentPermissionAssign,
    current_user: User = Depends(require_permissions(["department:permission:update"]))
):
    """添加部门权限（保留现有权限）"""
    try:
        await DepartmentService.update_department_permissions(
            department_id=department_id,
            permission_ids=permissions.permission_ids
        )
        
        return ResponseBase(message="部门权限添加成功")
    except ValueError as e:
        raise HTTPException(status_code=400, detail=str(e))
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"添加部门权限失败: {str(e)}")

@router.delete("/department/{department_id}/permissions", response_model=ResponseBase, summary="移除部门权限")
async def remove_department_permissions(
    department_id: str,
    permissions: DepartmentPermissionAssign,
    current_user: User = Depends(require_permissions(["department:permission:update"]))
):
    """从部门移除指定权限"""
    try:
        await DepartmentService.remove_permissions_from_department(
            department_id=department_id,
            permission_ids=permissions.permission_ids
        )
        
        return ResponseBase(message="部门权限移除成功")
    except ValueError as e:
        raise HTTPException(status_code=400, detail=str(e))
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"移除部门权限失败: {str(e)}")

@router.get("/department/{department_id}/with-permissions", response_model=ResponseBase[DepartmentWithPermissions], summary="获取部门详情（包含权限）")
async def get_department_with_permissions(
    department_id: str,
    current_user: User = Depends(require_permissions(["department:list", "department:permission:list"]))
):
    """获取部门详情，包含权限信息"""
    try:
        department = await DepartmentService.get_department_by_id(department_id)
        if not department:
            raise HTTPException(status_code=404, detail="部门不存在")
            
        # 获取父部门信息
        parent = None
        if department.parent_id:
            parent = await DepartmentService.get_department_by_id(department.parent_id)
            
        # 获取部门权限
        await department.fetch_related("permissions")
        
        permission_list = [
            PermissionOut(
                id=perm.id,
                name=perm.name,
                code=perm.code,
                description=perm.description,
                created_at=str(perm.created_at),
                updated_at=str(perm.updated_at)
            )
            for perm in department.permissions
        ]
            
        return ResponseBase[DepartmentWithPermissions](
            data=DepartmentWithPermissions(
                id=department.id,
                dept_id=department.dept_id,
                dept_name=department.dept_name,
                description=department.description,
                parent_id=department.parent_id,
                parent_name=parent.dept_name if parent else None,
                order_num=department.order_num,
                ancestors=department.ancestors,
                level=department.level,
                created_at=str(department.created_at),
                updated_at=str(department.updated_at),
                permissions=permission_list
            )
        )
    except ValueError as e:
        raise HTTPException(status_code=404, detail=str(e))
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取部门详情失败: {str(e)}") 